<!--自定义函数判断权限-->
var userInfo = getAuthority();
var powerlist = JSON.parse(userInfo).permissions;
/*自定义函数判断权限*/
template.defaults.imports.hasPower = function(data){
    if(powerlist.includes(data)){
        return true;
    }
    return false;
};

layui.use(['layer', 'form', 'table', 'util', 'dtree','laypage'], function () {
    var $ = layui.jquery;
    var layer = layui.layer;
    var form = layui.form;
    var admin = layui.admin;
    var table = layui.table;
    var util = layui.util;
    var dtree = layui.dtree;
    var laypage = layui.laypage;
    var Authorization;//请求接口用
    var count = 0;//总个数
    var current=1;//当前页
    var fistRenderPage= true;//是否第一次渲染分页
    var reportData;//报告类型存储
    //获取权限方法
    if(userInfo){
        var access_token = localStorage.getExpire("access_token");
        var token_type = localStorage.getExpire("token_type");
        Authorization = token_type+" "+access_token;
        getSelectReports();
        getTableClassifyPower();
        getTablePower();
    }


    form.verify({
        code: function(value, item){ //value：表单的值、item：表单的DOM对象
            if(value<11){
                return '分类代码必须是整数，且必须大于等于11';
            }
        }
    });
    form.on('select(province)', function(dataObj){
        let report_type = "";
        if(dataObj.value){
            report_type = dataObj.value
        }
        getTableClassifyList(report_type)
    })
    //获取下拉列表
    function getSelectReports(){
        axios({
            method: 'get',
            url:metadataUrl.tableClassify.reportTableClassify,
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    var data = response.data.data;
                    reportData = data
                    var str = template("template-microGroup-tmpl",{reportData});
                    document.getElementById("province").innerHTML = str;
                    form.render('select')
                    getTableClassifyList("");
                }
            })
            .catch(function (error) {
                console.log(error);
            });
    }
    // 添加
    $('#addClassify').click(function () {
        showAddModel();
    });

    // 工具条点击事件
    table.on('tool(tableTbTree)', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;
        if (layEvent === 'edit') { // 修改
            showEditModel(data);
        } else if (layEvent === 'del') { // 删除
            doDel(obj);
        }
    });

    //获取表格数据
    function getTableClassifyList(reportType) {
        var req={
            current: current,
            size: pageSize,
            report_type:reportType?reportType:""
        };
        axios.get(metadataUrl.tableClassify.tableClassifyList,{
            params: req,
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){                   
                    var data = response.data.data;                    
                    renderTable(data);
                }
            })
            .catch(function (error) {
                console.log(error);
            });
    }
    function getTableClassifyPower() {
        var str = template("tableClassify-tmpl",{});
        document.getElementById("tableClassify-tmpl-box").innerHTML = str;
        form.render('select')
    }

    function getTablePower() {
        var str = template("tablePower-tmpl",{});
        document.getElementById("tablePower-tmpl-box").innerHTML = str;
    }

    function renderTable(listData) {
        // 渲染表格
        var insTb = table.render({
            elem: '#tableTbTree',
            size: 'sm', //小尺寸的表格
            data:listData.records,
            cols: [[
                {type:'numbers',align: 'center', title: '#'},
                {field: 'name', align: 'center',  title: '名称'},
                {field: 'reportType', align: 'center', title: '报告期类型',templet:function (d) {
                        for (let i = 0;i<reportData.length;i++){
                            if(d.reportType == reportData[i].value){
                                return reportData[i].key
                            }
                        }

                    }},
                {field: 'memo', align: 'center',  title: '描述',minWidth: 120},
                {align: 'center', toolbar: '#tablePower-tmpl-box', title: '操作', minWidth: 120}
            ]]
        });
        if(fistRenderPage){
            laypage.render({
                elem: 'page-box'
                ,count: listData.total,
                limit:listData.size,
                groups:1,
                current:current
                ,layout: ['count','prev','page', 'next']
                ,jump: function(obj, first){
                    if(!first){
                        current = obj.curr;
                        fistRenderPage = false;
                        getTableClassifyList("");
                    }
                }
            });
        }
    }

    // 删除
    function doDel(obj) {
        layer.confirm('确定要删除"' + obj.data.name + '"？', {
            skin: 'layui-layer-admin',
            shade: .1
        }, function (i) {
            layer.close(i);
            layer.load(2);
            axios({
                method: 'delete',
                url:metadataUrl.tableClassify.deleteTableClassify + obj.data.id,
                headers:{
                    'Authorization':Authorization
                }
            })
                .then(function (res) {
                    if (res.status == 200&&res.data.message=="success") {
                        fistRenderPage = true
                        layer.closeAll('loading');
                        layer.msg("成功删除", {icon: 1});
                        getTableClassifyList("");
                    } else {
                        layer.closeAll('loading');
                        layer.msg(res.data.message, {icon: 2});
                    }
                })
                .catch(function (err) {
                    console.log(err);
                })
        });
    }

    // 显示编辑表单弹窗
    function showEditModel(mRole) {        
        admin.open({
            type: 1,
            title: '编辑数据模板',
            area: ['350px', '480px'],
            content: $('#editClassifyForm').html(),
            success: function (layero, dIndex) {
                var str = template("template-micro-tmpl",{reportData});
                document.getElementById("editReport-box").innerHTML = str;
                form.render('select')                            
                form.val('modelUserForm', mRole);  // 回显数据
                // 表单提交事件
                form.on('submit(editUserModelForm)', function (data) {
                    layer.load(2);
                    let formData = mRole;
                    formData.name = data.field.name;
                    formData.memo = data.field.memo;
                    formData.reportType = data.field.reportType;
                    axios({
                        method: 'put',
                        data:formData,
                        url:metadataUrl.tableClassify.editTableClassify,
                        headers:{
                            'Authorization':Authorization
                        }
                    })
                        .then(function (res) {
                            if (res.status == 200&&res.data.message=="success") {
                                getTableClassifyList("");
                                layer.closeAll('loading');
                                layer.close(dIndex);
                                layer.msg("编辑成功", {icon: 1});
                            } else {
                                layer.closeAll('loading');
                                layer.msg(res.data.message, {icon: 2});
                            }
                        })
                        .catch(function (err) {
                            console.log(err);
                        })
                    return false;
                });
            }
        });
    }

    function showAddModel() {
        admin.open({
            type: 1,
            title: '新增数据模板',
            area: ['350px', '480px'],
            offset:'auto',
            content: $('#addClassifyForm').html(),
            success: function (layero, dIndex) {
                form.verify({
                    code: function(value, item){ //value：表单的值、item：表单的DOM对象
                        if(value<11){
                            return '分类代码必须是整数，且必须大于等于11';
                        }
                    }
                });
                // var url = mRole ? '../../json/ok.json' : '../../json/ok.json';
                // form.val('modelRoleForm', mRole);  // 回显数据
                // 表单提交事件

                var str = template("template-micro-tmpl",{reportData});
                document.getElementById("addReport-box").innerHTML = str;
                form.render('select')
                form.on('submit(modelSubmitUser)', function (data) {
                    layer.load(2);
                    let formData = data.field;
                    axios({
                        method: 'post',
                        data:formData,
                        url:metadataUrl.tableClassify.addTableClassify,
                        headers:{
                            'Authorization':Authorization
                        }
                    })
                        .then(function (res) {
                            if (res.status == 200&&res.data.message=="success") {
                                fistRenderPage = true
                                getTableClassifyList("");

                                layer.close(dIndex);
                                layer.msg("新增成功", {icon: 1});
                            } else {

                                layer.msg(res.data.message, {icon: 2});
                            }
                            layer.closeAll('loading');
                        })
                        .catch(function (err) {
                            console.log(err);
                        })
                    return false;
                });
            }
        });
    }
});







